#include "render/scene2D.h"
#include "render/render_system.h"
#include <opengl/opengl_shader.h>
#include "entity/point_entity.h"
#include "entity/line_entity.h"
#include "entity/triangle_entity.h"
#include "entity/sprite.h"
#include "entity/cube.h"
#include "entity/panel.h"
#include "entity/camera.h"

namespace engine
{

    Sprite *sprite;
    Sprite *player;

    Scene2D::Scene2D()
    {
        this->shader = RenderSystem::getInstance()->loadShader("word2d", "./assets/shader/world2D.vs", "./assets/shader/world2D.fs", NULL);
        this->objectRoot = new Object2D(); // 场景跟对象
        this->camera = new Camera();       // 创建相机
        this->camera->setPosition(0.0f, 0.0f, 10.0f);
        this->shader->use();
        // 投影矩阵
        shader->setMatrix4("projection", glm::perspective(glm::radians(45.0f), (float)800 / (float)600, 0.1f, 100.0f));
        // sprite = new Sprite();
        Texture2D *tex = RenderSystem::getInstance()->loadTexture("container", "./assets/texture/container.jpg", GL_FALSE);
        sprite = new Sprite(this->shader, tex);
        sprite->setScale(100, 100);
        player = new Sprite(this->shader, RenderSystem::getInstance()->loadTexture("awesomeface", "./assets/texture/awesomeface.png", GL_FALSE));
        this->addObject(sprite);
        this->addObject(player);
        // glEnable(GL_DEPTH_TEST);
    }

    Scene2D::~Scene2D()
    {
    }

    void Scene2D::render(double time)
    {
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        // glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        // render
        this->shader->use();
        // 视口矩阵
        shader->setMatrix4("view", this->camera->getViewMatrix());
        for (int i = 0; i < objectRoot->mChildren.size(); i++)
        {
            ((Entity2D *)(objectRoot->mChildren[i]))->render();
        }
    }

    void Scene2D::addObject(Object2D *object)
    {
        if (this->objectRoot != NULL)
        {
            this->objectRoot->addChildren(object);
        }
    }

    // 处理输入
    void Scene2D::processInput(GLFWwindow *window)
    {
        if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
            glfwSetWindowShouldClose(window, true);

        float cameraSpeed = 0.05f; // adjust accordingly
        if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
            camera->move(0, 0, -cameraSpeed);
        if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
            camera->move(0, 0, cameraSpeed);
        if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
            camera->move(-cameraSpeed, 0, 0);
        if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
            camera->move(cameraSpeed, 0, 0);
    }
}